<?php
include 'Generator.class.php';

class WeddingXML {
	
	var $xml;
	var $filename = 'contacts.xml';
	
	function __construct() {
		//config should automagically be loaded by any script that includes this class
		$c = new Config;
		$this->xml  = simplexml_load_file($c->baseDIR.$this->filename);
	}
	
	// lazy magic funtion
	function __get($var) {
		return $this->$var;
	}
	
	function checkCode($code){
		$code = strtoupper($code); // codes are stored using caps only
		$res = $this->xml->xpath('//invite[code="'.$code.'"]');
		return $res;
	}
	
	private function _saveXML() {
		return $this->xml->asXML($c->baseDIR.$this->filename);
	}
	
	function setAttending($node,$val=0) {
		if($val) {
			$state = 1;
		} else { 
			$state = 0;	
		}
		$node[0]->attending = $state;
		return $this->_saveXML();
	}
	/**
	 * 
	 * @return multitype:string
	 * returns codes already used in the XML
	 */
	
	function getCodes() {
		$codesUsed = array();
		foreach($this->xml->xpath('//code') as $e) {
			$tmp = (string)$e;
			if(strlen($tmp) > 0)
				$codesUsed[] = $tmp;
		}
		return $codesUsed;
	}
	
	/**
	 * Assigns codes to nodes without
	 */
	function assignCodes() {
		$g = new Generator();
		// get existing codes from the XML
		$uc = self::getCodes();
		// get the codes we need to update
		$e2up = $this->xml->xpath('//invite/code[not(text())]');
		
		if(count($e2up) < 1) {
			// nothing to do, exit
			return false;
		}
		
		// get some unique codes
		$codes = $g->generateCodes(count($e2up),4,$uc);
		
		foreach($e2up as $e) {
			if(is_array($codes)) {
				$tmpcode = array_pop($codes);
			} else {
				$tmpcode = $codes;
			}
			$e[0] = $tmpcode;
		}	
		return $this->_saveXML();
	}
}